import axios from 'axios'
import { Message, Notification } from 'element-ui'
import router from '@/router'
import store from '@/store'

// axios 全局配置
axios.defaults.timeout = process.env.API_TIME_OUT
axios.defaults.baseURL = `${process.env.API_PATH}/api/`

// axios http request 拦截器
axios.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    const ShopID = sessionStorage.getItem('currentShopID')
    config.data = JSON.stringify(config.data)
    config.headers = {
      'Content-Type': 'application/json; charset=UTF-8'
    }
    if (token) {
      config.headers.token = token
    }
    if (ShopID) {
      config.headers.ShopID = ShopID
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// 异常处理参数配置
const responseExceptionCode = {
  ECONNABORTED: { // 远程主机拒绝网络连接
    title: '请求超时',
    text: '远程主机拒绝网络连接！',
    type: 'error',
    confirmButtonText: '重新加载',
    showCancelButton: false,
    confirmEvent: () => {
      window.location.reload()
    }
  },
  ERR_CONNECTION_TIMED_OUT: { // 服务器连接超时，请稍后重试！
    title: '请求超时',
    text: '服务器连接超时，请稍后重试！',
    type: 'error',
    confirmButtonText: '重新加载',
    showCancelButton: false,
    confirmEvent: () => {
      window.location.reload()
    }
  },
  ERR_INTERNET_DISCONNECTED: {
    title: '网络异常',
    text: '网络连接异常，请检查网络是否接通！',
    type: 'error',
    confirmButtonText: '重新加载',
    showCancelButton: false,
    confirmEvent: () => {
      window.location.reload()
    }
  },
  RUNTIMEEXCEPTION: { // 运行时异常
    title: '系统繁忙',
    text: '服务器开小差了，请稍后再次尝试！',
    type: 'warning',
    confirmButtonText: '知道了',
    showCancelButton: false
  }
}
/**
 * 异常处理确认操作框
 * @param {*} code 错误码
 */
const ExceptionConfirm = (code) => {
  let Exception = responseExceptionCode[code]
  if (Exception) {
    return Exception.text
  } else {
    return ExceptionConfirm('RUNTIMEEXCEPTION')
  }
}
/**
 * 异常适配处理
 * @param {*} error
 */
const responseExceptionCatach = (error) => {
  return ExceptionConfirm(error.code)
}
// axios http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      if (error.response.status !== 200) {
        if (error.response.status === 401) {
          if (error.response.data.Code === 100003) { // 登录失效
            Message.error('登录授权已失效，请重新登录！')
            store.dispatch('AdminLogoutAction').then(() => {
              router.replace('/login')
            })
          } else if (error.response.data.Code === 100004 || error.response.data.Code === 160011) { // 没有权限
            Notification.error({
              title: '访问受限',
              message: `错误码：${error.response.data.Code}`,
              duration: 0
            })
          } else if (error.response.data.Code === 160003) { // 商户未找到
            Notification.error({
              title: '商户不存在',
              message: `错误码：${error.response.data.Code}`,
              duration: 0
            })
            router.replace('/')
          } else {
            Message.error(`${error.response.data.Message}-错误码:${error.response.data.Code}`)
          }
        } else {
          console.log(error.response)
          Message.error(`${error.response.data.Message}-错误码:${error.response.status}`)
        }
      }
      return Promise.resolve({
        data: {
          Code: 500,
          Msg: '系统异常'
        }
      })
    } else {
      return Promise.resolve({
        data: {
          Code: 500,
          Msg: responseExceptionCatach(error)
        }
      })
    }
  }
)

export default {
  /**
   * get 请求
   * @param {*} url
   * @param {*} params
   */
  get (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params
      }).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * post 请求
   * @param {*} url
   * @param {*} data
   */
  post (url, data = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, data).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * put 请求
   * @param {*} url
   * @param {*} data
   */
  put (url, data = {}) {
    return new Promise((resolve, reject) => {
      axios.put(url, data).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
 * delete 请求
 * @param {*} url
 * @param {*} data
 */
  delete (url, data = {}) {
    return new Promise((resolve, reject) => {
      axios.delete(url, data).then(response => {
        resolve(response.data)
      }).catch(err => {
        reject(err)
      })
    })
  }
}
